
package com.kanjian.music.fragment;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.kanjian.music.R;
import com.kanjian.music.activity.BaseActivity;
import com.kanjian.music.adapter.FeedListAdapter;
import com.kanjian.music.api.ApiRequestManager;
import com.kanjian.music.constants.IntentConstants;
import com.kanjian.music.entity.Feed;
import com.kanjian.music.network.HttpLoader;

/**
 * 邂逅
 * 
 * @author xuyanjun@kanjian.com
 */
public class FeedFragment extends MusicSubBaseFragment implements LoaderCallbacks<String> {

    private View mRootView;

    private FeedListAdapter mListAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            initView(inflater, container);
        }
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    private void initView(LayoutInflater inflater, ViewGroup container) {
        mRootView = inflater.inflate(R.layout.fragment_feed, container, false);
        mListView = (ListView) mRootView.findViewById(R.id.feed_listview);
        mListAdapter = new FeedListAdapter(getActivity(), mListView, (BaseActivity) getActivity());
        mListView.setAdapter(mListAdapter);
        setListScrollListener();
        Bundle args = new Bundle();
        args.putSerializable(IntentConstants.HTTPLOADERREQUESTPARAM,
                ApiRequestManager.getFeedRequest(0));
        getLoaderManager().initLoader(0, args, this);
    }

    public void onDestroyView() {
        super.onDestroyView();
        mRootView = null;
    }

    @Override
    public Loader<String> onCreateLoader(int id, Bundle args) {
        return new HttpLoader(getActivity(), args);
    }

    @Override
    public void onLoadFinished(Loader<String> loader, String data) {
        if (data != null) {
            ArrayList<Feed> feedList = Feed.getFeedListFromJson(data);
            if (feedList != null) {
                mListAdapter.setDataList(feedList);
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<String> loader) {
    };
}
